package com.liutaw.nanjingair.views.viewcomponent;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.liutaw.nanjingair.R;

/**
 * Created by liutao on 15/12/23.
 */
public class LoadingView {
    private ViewGroup decorView;
    private boolean isShowing = false;
    private Activity activity;
    private View view;

    public LoadingView(Activity activity) {
        this.activity = activity;
        init();
    }

    private void init() {
        decorView = (ViewGroup) this.activity.getWindow().getDecorView().findViewById(android.R.id.content);
        view = LayoutInflater.from(activity).inflate(R.layout.layout_loading_view, null);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //什么也不做
            }
        });
    }

    public void show() {
       show(false);
    }

    public void show(boolean isEmpty) {
        View view_bg = view.findViewById(R.id.view_bg);
        if (isEmpty) {
            view_bg.setVisibility(View.GONE);
        } else {
            view_bg.setVisibility(View.VISIBLE);
        }
        //开始动画
        if (isShowing) {
            return;
        }
        isShowing = true;

        if (view.getParent() == null) {
            decorView.addView(view);
        }
        decorView.postDelayed(new Runnable() {
            @Override
            public void run() {
                dismiss();
            }
        }, 500);
    }

    public void showForever() {
        //开始动画
        if (isShowing) {
            return;
        }
        isShowing = true;

        if (view.getParent() == null) {
            decorView.addView(view);
        }
//        decorView.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                dismiss();
//            }
//        }, 500);
    }

    public void dismiss() {
        if (!isShowing) {
            return;
        }
        isShowing = false;
        if (view.getParent() != null) {
            decorView.removeView(view);
        }
    }
}
